import { message } from 'antd';

// 定义请求配置接口
interface RequestConfig extends RequestInit {
  timeout?: number;
  showError?: boolean;
}

// 定义响应数据接口
interface ResponseData<T = any> {
  code: number;
  data: T;
  message: string;
}

// 基础配置
const DEFAULT_CONFIG: RequestConfig = {
  timeout: 10000,
  showError: true,
};

// 错误处理
const handleError = (error: any, showError: boolean = true) => {
  if (showError) {
    message.error(error.message || '请求失败');
  }
  return Promise.reject(error);
};

// 超时处理
const timeoutPromise = (timeout: number) => {
  return new Promise((_, reject) => {
    setTimeout(() => {
      reject(new Error(`请求超时 ${timeout}ms`));
    }, timeout);
  });
};

// 请求拦截器
const requestInterceptor = (config: RequestConfig) => {
  // 这里可以添加token等认证信息
  const token = localStorage.getItem('token');
  if (token) {
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${token}`,
    };
  }
  return config;
};

// 响应拦截器
const responseInterceptor = async (response: Response) => {
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const data = await response.json();
  if (data.code !== 0) {
    throw new Error(data.message || '请求失败');
  }
  return data;
};

// 基础请求方法
const request = async <T = any>(
  url: string,
  config: RequestConfig = {}
): Promise<ResponseData<T>> => {
  const finalConfig = {
    ...DEFAULT_CONFIG,
    ...config,
  };

  try {
    // 应用请求拦截器
    const interceptedConfig = requestInterceptor(finalConfig);

    // 发起请求
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), finalConfig.timeout);

    const response = await Promise.race([
      fetch(url, {
        ...interceptedConfig,
        signal: controller.signal,
      }),
      timeoutPromise(finalConfig.timeout!),
    ]) as Response;

    clearTimeout(timeoutId);

    // 应用响应拦截器
    const data = await responseInterceptor(response);
    return data;
  } catch (error: any) {
    return handleError(error, finalConfig.showError);
  }
};

// GET 请求
export const get = <T = any>(
  url: string,
  params?: Record<string, any>,
  config: RequestConfig = {}
) => {
  const queryString = params
    ? `?${new URLSearchParams(params).toString()}`
    : '';
  return request<T>(`${url}${queryString}`, {
    ...config,
    method: 'GET',
  });
};

// POST 请求
export const post = <T = any>(
  url: string,
  data?: any,
  config: RequestConfig = {}
) => {
  return request<T>(url, {
    ...config,
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json',
      ...config.headers,
    },
  });
};

// PUT 请求
export const put = <T = any>(
  url: string,
  data?: any,
  config: RequestConfig = {}
) => {
  return request<T>(url, {
    ...config,
    method: 'PUT',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json',
      ...config.headers,
    },
  });
};

// DELETE 请求
export const del = <T = any>(
  url: string,
  config: RequestConfig = {}
) => {
  return request<T>(url, {
    ...config,
    method: 'DELETE',
  });
};

// 导出默认对象
export default {
  get,
  post,
  put,
  delete: del,
}; 